
package com.cssy.xxkj.logic.util;


import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.plat.util.ConvertUtils;


public class ExcelUtils
{
	public  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public  String sheetName = null;
	
	private  DecimalFormat df = new DecimalFormat("#.000");
	
	public  void toExcel(List entitys, String reflectExcel, String excelName, HttpServletResponse response)
	{
		
		List rowNameList = new ArrayList();
		List propertyNameList = new ArrayList();
		String[] columns;
		if (reflectExcel.split("┋").length > 0)
			columns = reflectExcel.split("┋");
		else {
			columns = reflectExcel.split(",");
		}
		for (String rowNameAndPropertyName : columns) {
			String[] rowNameAndPropertyNameArr = rowNameAndPropertyName
					.split(":");
			rowNameList.add(rowNameAndPropertyNameArr[0].trim());
			propertyNameList.add(rowNameAndPropertyNameArr[1].trim());
		}
		
		response.setContentType("text/html;charset=UTF-8");
		response.reset();
		response.setContentType("application/ms-excel");
		String fileNameDisplay = excelName + 
				new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"), 
					"iso-8859-1");
		}
		catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			sheetName = null;
		}
		fileNameDisplay = fileNameDisplay.replace(" ", "%20");
		response.addHeader("Content-Disposition", "attachment;filename=" + 
				fileNameDisplay + ".xls");
		HSSFWorkbook wb = null;
		Object fout = null;
		try {
			wb = creatExcel(entitys, rowNameList, propertyNameList);
			fout = response.getOutputStream();
			wb.write(response.getOutputStream());
			((OutputStream)fout).flush();
			((OutputStream)fout).close();
			sheetName = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public  HSSFWorkbook creatExcel(List entitys, List rowNameList, List propertyNameList)
	{
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFCellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setBorderBottom((short) 1);
		cellStyle.setBorderLeft((short) 1);
		cellStyle.setBorderRight((short) 1);
		cellStyle.setBorderTop((short) 1);
		cellStyle.setAlignment((short) 2);
		cellStyle.setVerticalAlignment((short)1);
		HSSFCellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment((short)2);
		headerStyle.setAlignment((short)2);
		headerStyle.setBorderBottom((short)1);
		headerStyle.setBorderLeft((short)1);
		headerStyle.setBorderRight((short)1);
		headerStyle.setBorderTop((short)1);
		headerStyle.setVerticalAlignment((short)1);
		HSSFFont bold1 = workbook.createFont();
		bold1.setFontName("黑体");
		bold1.setFontHeightInPoints((short) 12);
		bold1.setBoldweight((short)50);
		headerStyle.setFont(bold1);
		headerStyle.setFillPattern((short)1);
		headerStyle.setFillForegroundColor((short)43);
		int colNum = 0;
		int sheetsNo = entitys.size() / 65534 + 1;
		for (int i = 0; i < sheetsNo; i++) {
			HSSFSheet sheet = null;
			if (sheetName != null)
				sheet = workbook.createSheet(sheetName);
			else {
				sheet = workbook.createSheet();
			}
			HSSFCell cell = null;
			HSSFRow row = sheet.createRow(0);
			for (int k = 0; k < rowNameList.size(); k++) {
				cell = row.createCell((short)(colNum++));
				cell.setCellStyle(headerStyle);
				cell.setCellValue(
						new HSSFRichTextString(rowNameList.get(k)
								.toString()));
			}
			colNum = 0;
		}
		int f=0;
		if (entitys.size() > 0) {
			Map getterMap = getClassGetterMap(entitys.get(0).getClass());
			for (int p = 0; p < entitys.size(); p++)
			{
				HSSFSheet sheet = workbook.getSheetAt(p / 65534);
				HSSFRow row = sheet.createRow(p % 65534 + 1);
				
				Object o = entitys.get(p);
				colNum = 0;
				for (int i = 0; i < propertyNameList.size(); i++) {
					HSSFCell cell = row.createCell((short)(colNum++));
					cell.setCellStyle(cellStyle);
					try
					{
						String key = propertyNameList.get(i).toString();
						
						Object value = ConvertUtils.IsNullValue(o, key);
						cell.setCellValue(
								new HSSFRichTextString(formatFieldValue(value)));
					}
					catch (Exception ex)
					{
						ex.printStackTrace();
					}
				}
			}
			
		}
		
		return workbook;
	}
	
	private  Map getClassGetterMap(Class cls) {
		Map getterMap = new HashMap();
		for (Field field : cls.getDeclaredFields()) {
			String key = field.getName();
			Method getter = null;
			String fieldClassName = field.getType().getSimpleName();
			String getterName;
			if ((fieldClassName.equals("boolean")) || (fieldClassName.equals("Boolean")))
				getterName = "is" + key.substring(0, 1).toUpperCase() + 
				key.substring(1);
			else
				getterName = "get" + key.substring(0, 1).toUpperCase() + 
				key.substring(1);
			try
			{
				getter = cls.getMethod(getterName, new Class[0]);
			}
			catch (NoSuchMethodException localNoSuchMethodException) {
			}
			getterMap.put(key.toUpperCase(), getter);
		}
		return getterMap;
	}
	
	private  String formatFieldValue(Object value) {
		if (value == null) {
			return "";
		}
		String className = value.getClass().getName();
		if ((className.equals("java.util.Date")) || 
				(className.equals("java.sql.Date")) || 
				(className.equals("java.sql.Timestamp")))
			return sdf.format(value);
		if ((className.equals("java.lang.Double")) && (value != null)) {
			BigDecimal num = new BigDecimal(Double.parseDouble(value.toString()));
			return format(num);
		}
		return value.toString();
	}
	
	public  void main(String[] args) {
		System.out.println("1222".indexOf("."));
	}
	
	private  String format(BigDecimal num)
	{
		if (num.toString().indexOf(".") != -1) {
			return df.format(num);
		}
		return num.toString();
	}
}
